#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <unistd.h>
using namespace std;

#include "Comm.hpp"

const int gdefaultid = -1;
const int gsize = 4096;
const string pathname = ".";
const int projid = 0x66;
const int gmode = 0666;

#define CREATER "creater"
#define USER "user"

class Shm
{
public:
    Shm(const string& pathname,int projid,const string& usertype)
        :_shmid(gdefaultid),
         _size(gsize),
         _start_mem(nullptr),
         _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if(_key < 0)
        {
            ERR_EXIT("fotk");
        }
        if(_usertype == CREATER)
        {   
            //创建共享内存
            Create();
        }
        else if(_usertype == USER)
        {
            //得到共享内存
            Get();
        }
        else
        {
            
        }
        //链接共享内存
        Attach();
    }

    void* VirtualAddr()
    {
        printf("VirtualAddr: %p\n", _start_mem);
        return _start_mem;
    }

    int Size()
    {
        return _size;
    }

    void Attr()
    {
        struct shmid_ds ds;
        //ds输出型参数
        int n = shmctl(_shmid, IPC_STAT, &ds);
        printf("shm_segsz: %ld\n", ds.shm_segsz);
        printf("key: 0x%x\n", ds.shm_perm.__key);
    }

    ~Shm()
    {
        cout << _usertype << endl;
        if(_usertype == CREATER)
        {
            Destroy();
        }
    }

private:
    //创建新的共享内存
    void CreateHelper(int flg)
    {
        printf("key: 0x%x\n", _key);
        //共享内存的生命周期，跟随内核
        _shmid = shmget(_key, _size, flg);
        if(_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _shmid);
    }

    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | gmode);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("attach success\n");
    }

    void Detach()
    {
        int n = shmdt(_start_mem);
        if(n == 0)
        {
            printf("detach success\n");
        }
    }

    void Get()
    {
        CreateHelper(IPC_CREAT);
    }

    void Destroy()
    {
        if(_shmid == gdefaultid)
        {
            return;
        }
        Detach();
        if(_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID,nullptr);
            if(n > 0)
            {
                printf("shmctl delete shm: %d success!\n", n);
            }
            else
            {
                ERR_EXIT("shmctl");
            }
        }
    }

private:
    int _shmid;
    key_t _key;
    int _size;
    void* _start_mem;
    string _usertype;
};